import { CODE, DB_ERROR } from "../config/code.js";

// ====================== 模块级别工具函数 ======================
export const getDefaultErrorCode = (error) => {
  if (error.message.includes("syntax") || error.message.includes("SQL")) {
    return 6008;
  } else if (error.message.includes("Connection closed")) {
    return 6009;
  } else if (error.message.includes("permission")) {
    return 3003;
  }
  return 5001;
};

export const error = (err) => {
  console.error("DB Error:", err);
  // 从映射表获取状态码或使用默认错误码
  const errorCode = DB_ERROR[err.code] || getDefaultErrorCode(err);

  return {
    success: false,
    msg: CODE[errorCode], // 从CODE对象获取错误消息
    code: errorCode,
    data: {
      sql: err.sql,
      sqlMessage: err.sqlMessage,
    },
  };
};

export const fail = (msg = CODE[201], data = {}) => {
  console.warn("Operation failed:", msg);
  return {
    success: false,
    msg,
    code: 201, // 使用通用失败码
    data,
  };
};

export const success = (data = {}, msg = CODE[200]) => ({
  success: true,
  msg,
  code: 200, // 使用标准成功码
  data,
});
